package com.baomidou.springwind.baidu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.springwind.entity.NetworkNode;
import com.baomidou.springwind.pojo.RouteInfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.*;

/**
 * Created by demo on 2017/8/7.
 */
@Component
public class RouteMatrix {
    private static final String AK = "NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG";

    public TreeSet<RouteInfo> getBaiduApiResult(NetworkNode origins, List<NetworkNode> destinations) {
        TreeSet<RouteInfo> result = new TreeSet<RouteInfo>(new Comparator<RouteInfo>() {
            @Override
            public int compare(RouteInfo o1, RouteInfo o2) {
                return o1.distance.intValue() - o2.distance.intValue();
            }
        });
        StringBuilder originsParam = new StringBuilder();
        StringBuilder destinationsParam = new StringBuilder();
        originsParam.append(origins.getCoordinateY()).append(",").append(origins.getCoordinateX());
        for (NetworkNode node : destinations) {
            destinationsParam.append(node.getCoordinateY()).append(",").append(node.getCoordinateX()).append("|");
        }
        destinationsParam.deleteCharAt(destinationsParam.lastIndexOf("|"));
        String url = String.format("http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=%s&destinations=%s&ak=%s", URLEncoder.encode(originsParam.toString()), URLEncoder.encode(destinationsParam.toString()), AK);
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = client.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String text = EntityUtils.toString(httpEntity);//取出应答字符串
                JSONObject json = JSONObject.parseObject(text);
                JSONArray array = json.getJSONArray("result");
                for (int i = 0; i < array.size(); i++) {
                    JSONObject distance = array.getJSONObject(i);
                    result.add(new RouteInfo(destinations.get(i).getId()
                            , distance.getJSONObject("distance").getLong("value")
                            , distance.getJSONObject("duration").getLong("value")
                    ));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
